{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import defaultdict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#排序（用字符作为键）：字母异位词是相同数量的字符的重排列，因此将字符排序后，字母异位词的键key（即字符本身）一样\n",
    "def algorithm1(strs):\n",
    "    sort_strs = defaultdict(list)                 # defaultdict输入对应字典值的格式：int为整数；list为数列\n",
    "    for st in strs:\n",
    "        key = \"\".join(sorted(st))                 # 字母异位词将被判为同一键key，放到该键对应的值下\n",
    "        sort_strs[key].append(st)\n",
    "    return list(sort_strs.values())               # 字典直接返回所有值\n",
    "\n",
    "#计数（用元组作为键）：字母异位词对应的每个字符数量一样，通过得到的每个字符的频率数组，进行分组\n",
    "def algorithm2(strs):\n",
    "    num_strs = defaultdict(list)\n",
    "    for st in strs:\n",
    "        count = [0]*26\n",
    "        for ch in st:\n",
    "            count[ord(ch)-ord('a')] +=1\n",
    "        key = tuple(count)                         # 只有不变数据类型才可以作为键\n",
    "        num_strs[key].append(st)\n",
    "    return list(num_strs.values())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "strs = [\"abbccc\",\"babccc\",\"cbbcac\",\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[['abbccc', 'babccc', 'cbbcac'],\n",
       " ['eat', 'tea', 'ate'],\n",
       " ['tan', 'nat'],\n",
       " ['bat']]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "algorithm1(strs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "algorithm2(strs) == algorithm1(strs)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
